package com.asia5b.a5mall.middleware.base

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.asia5b.a5mall.middleware.api.ApiManager.API_AFTERSALE
import com.asia5b.a5mall.middleware.api.ApiManager.API_BASE
import com.asia5b.a5mall.middleware.api.ApiManager.API_CART
import com.asia5b.a5mall.middleware.api.ApiManager.API_CATEGORY
import com.asia5b.a5mall.middleware.api.ApiManager.API_EXTRA
import com.asia5b.a5mall.middleware.api.ApiManager.API_GOODS
import com.asia5b.a5mall.middleware.api.ApiManager.API_MEMBER
import com.asia5b.a5mall.middleware.api.ApiManager.API_ORDER
import com.asia5b.a5mall.middleware.api.ApiManager.API_PASSPORT
import com.asia5b.a5mall.middleware.api.ApiManager.API_PAYMENT
import com.asia5b.a5mall.middleware.api.ApiManager.API_PROMOTION
import com.asia5b.a5mall.middleware.api.ApiManager.API_SHOP
import com.asia5b.a5mall.middleware.api.ApiManager.API_TRADE
import com.asia5b.a5mall.middleware.api.ApiErrorHelper
import com.asia5b.a5mall.middleware.api.CustomThrowable
import com.asia5b.a5mall.middleware.utils.showMessage
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer

/**
 * Created by zhangyuncai on 2020/8/19.
 */
open class SimpleViewModel : ViewModel() {
    val goodsApi = API_GOODS
    val memberApi = API_MEMBER
    val extraApi = API_EXTRA
    val baseApi = API_BASE
    val afterSaleApi = API_AFTERSALE
    val cartApi = API_CART
    val categoryApi = API_CATEGORY
    val orderApi = API_ORDER
    val paymentApi = API_PAYMENT
    val promotionApi = API_PROMOTION
    val shopApi = API_SHOP
    val tradeApi = API_TRADE
    val passportApi = API_PASSPORT
    val application by lazy {
        BaseApplication.sApplication
    }
    val context by lazy {
        BaseApplication.sContext
    }
    protected val compositeDisposable = CompositeDisposable()
    var loadingLiveData = MutableLiveData<Int>()


    protected val requestMap = hashMapOf<String, Disposable>()

    fun dismissLoadingBar() {
        loadingLiveData.value = 1
    }

    protected fun <T> baseSubscribe(observable: Observable<T>, resultConsumer: Consumer<T>) {
        baseSubscribe(observable, SimpleNetParams(), resultConsumer, null)
    }

    protected fun <T> baseSubscribe(observable: Observable<T>, netParams: SimpleNetParams, resultConsumer: Consumer<T>) {
        baseSubscribe(observable, netParams, resultConsumer, null)
    }


    fun <T> baseSubscribe(observable: Observable<T>,
                          netParams: SimpleNetParams,
                          resultConsumer: Consumer<T>,
                          throwableConsumer: Consumer<Throwable>?) {
        netParams.loadingLiveData = loadingLiveData
        if (!TextUtils.isEmpty(netParams.requestTag) && requestMap.containsKey(netParams.requestTag!!)) {
            requestMap.get(netParams.requestTag!!)?.dispose()
        }
        val subscribe = observable.compose(SimpleTransformer<T>(netParams))
                .subscribe({
                    //到了这里一定是有数据的
                    resultConsumer.accept(it)
                }, {
                    //提供给基类并打印日志
                    loadingLiveData.value = 2

                    //todo 后台通过500报错返回前端提示错误
                    val customThrowable = CustomThrowable.newInstance(it)
                    //返回错误日志给使用者
                    throwableConsumer?.accept(customThrowable ?: it)

                    //提示错误日志
                    if (customThrowable != null &&
                            customThrowable!!.errResultModel != null &&
                            !TextUtils.isEmpty(customThrowable!!.errResultModel!!.message)
                    ) {
                        if (customThrowable!!.errResultModel!!.code != "475") {
                            if (netParams.isToastError) {
                                showMessage(customThrowable!!.errResultModel!!.message)
                            }
                        }
                    } else {
                        if (netParams.isToastError) {
                            ApiErrorHelper.handleCommonError(it)
                        }
                    }
                })
        if (!TextUtils.isEmpty(netParams.requestTag)) {
            requestMap.put(netParams.requestTag!!, subscribe)
        }
        compositeDisposable.add(subscribe)
    }

    override fun onCleared() {
        super.onCleared()
        compositeDisposable.dispose()
    }

}